import { usePublicHooks } from "../../hooks";
import { usePublicFormats } from "../../formats";

import { reactive, onMounted, h, toRaw } from "vue";
import { delay } from "@pureadmin/utils";
import {
  whiteList,
  whiteListAdd,
  whiteListDelete,
  download
} from "@/api/white_list";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import editForm from "../form.vue";
import type { FormItemProps } from "./types";

export function reconciliationConfig() {
  const form = reactive({
    name: "",
    mobile: "",
    car_number: "",
    car_no_color: -1,
    car_type: -1,
    page: 1,
    limit: 20
  });

  //从父级钩子里取东西
  const { pagination, loadingConfig, dataList, formRef, loading } =
    usePublicHooks();

  const { carColorShow, carTypeShow, orderTypeShow } = usePublicFormats();

  const columns: TableColumnList = [
    {
      label: "名称",
      prop: "name"
    },
    {
      label: "手机号",
      prop: "mobile"
    },
    {
      label: "车牌号",
      prop: "car_number"
    },
    {
      label: "车牌颜色",
      prop: "car_no_color",
      cellRenderer: ({ row }) => {
        return carColorShow(row.car_no_color);
      }
    },
    {
      label: "车型",
      prop: "car_type",
      cellRenderer: ({ row }) => {
        return carTypeShow(row.car_type);
      }
    },
    {
      label: "客户类型",
      prop: "order_type",
      cellRenderer: ({ row }) => {
        return orderTypeShow(row.order_type);
      }
    },
    {
      label: "有效期",
      prop: "out_time"
    },
    {
      label: "操作",
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const { data } = await whiteList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  //页面加载
  onMounted(() => {
    onSearch();
  });

  //页面条数变化
  function onSizeChange(val) {
    form.limit = val;
    onSearch();
  }

  //页码变化
  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      form.page = val;
      onSearch();

      //刷新数据
      loading.value = false;
    });
  }

  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      width: "30%",
      title: "导入数据",
      contentRenderer: () => h(editForm, { ref: formRef }),
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          mobile: row?.mobile ?? "",
          car_number: row?.car_number ?? "",
          car_no_color: row?.car_no_color ?? "",
          car_type: row?.car_type ?? ""
        }
      },
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              whiteListAdd(curData).then(() => {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              });
            }
          }
        });
      }
    });
  }

  const handleDelete = row => {
    whiteListDelete({
      id: row.id
    }).then(() => {
      onSearch();
    });
  };

  function handleDownload() {
    download(toRaw(form)).then(res => {
      try {
        // 调用 downRequest 请求文件
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "白名单导出.xlsx"); // 设置默认文件名
        document.body.appendChild(link);
        link.click();
        // 清理 URL 对象
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error("下载失败:", error);
      }
    });
  }

  return {
    columns,
    form,
    loading,
    onSearch,
    resetForm,
    dataList,
    pagination,
    onSizeChange,
    onCurrentChange,
    loadingConfig,
    openDialog,
    handleDelete,
    handleDownload
  };
}
